﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Windows.Threading;
using CSharp.Libs.Koc.KernelModels;
using CSharp.Libs.Koc.Models;
using CSharp.Libs.Koc.UserControls.ItemClasses;
using CSharp.Libs.WPF;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Media;
using System.Diagnostics;


namespace CSharp.Libs.Koc.UserControls
{
    /// <summary>KocReportGetterViewModel</summary>
    /// <remarks>report watcher part</remarks>
    /// <history>created  07.02.2012</history>
    public partial class KocReportGetterViewModel : ViewModelBase
    {
        #region declarations
        private Dictionary<string, ReportItem> _dictReportCache = new Dictionary<string, ReportItem>();
        private Dictionary<int, string> _dictCityNames = new Dictionary<int, string>();
        private Dictionary<int, string> _dictPlayerNames = new Dictionary<int, string>();
        private Dictionary<int, string> _dictAllianceNames = new Dictionary<int, string>();

        private System.Timers.Timer _tmrReportCheck = new System.Timers.Timer(10000);

        private Thread _thrReceiveReports = null;

        private bool _fReportWatcherActive = false;
        private bool _fAlertToAllianceChat = true;
        private bool _fAlertPlaySound = true;
        private bool _fLoggingEnabled = false;
        private int _intReportPagesToCheck = 3;
        private int _intReportsToCache = 500;
        private int _intAttackTroopCountMin = 10;
        private string _strAlertText = "";

        //constants
        public const string LAO_REPORT_WATCHER_PAGES_TO_CHECK = "ReportWatcherPagesToCheck";
        public const string LAO_REPORT_WATCHER_REPORTS_TO_CACHE = "ReportsToCache";
        public const string LAO_REPORT_WATCHER_TROOP_COUNT_MIN = "MinimumTroopCount";
        public const string LAO_ALERT_TO_ALLIANCE_CHAT = "AlertToAllianceChat";
        public const string LAO_ALERT_PLAY_SOUND = "AlertPlaySound";

        private const string ALERT_SOUND_FILE_NAME = "AlertSound.wav";

        private const string ALERT_TEXT_FILE_NAME = "AlertText.txt";
        private const string ALERT_PLACE_REPORT_ID = "<ReportID>";
        private const string ALERT_PLACE_S0_COORDS = "<S0Coords>";
        private const string ALERT_PLACE_S0_ALLIANCE_NAME = "<S0AllianceName>";
        private const string ALERT_PLACE_S0_PLAYER_NAME = "<S0PlayerName>";
        private const string ALERT_PLACE_S0_CITY_NAME = "<S0CityName>";
        private const string ALERT_PLACE_S1_COORDS = "<S1Coords>";
        private const string ALERT_PLACE_S1_ALLIANCE_NAME = "<S1AllianceName>";
        private const string ALERT_PLACE_S1_PLAYER_NAME = "<S1PlayerName>";
        private const string ALERT_PLACE_S1_CITY_NAME = "<S1CityName>";
        private const string ALERT_PLACE_S1_TROOP_COUNT = "<S1TroopCount>";

        //classes
        private class ReportDetails
        {
            public ReportDetails(
                int _OffensiveTroopCount)
            {
                OffensiveTroopCount = _OffensiveTroopCount;
            }
            int OffensiveTroopCount { get; set; }
        }
        #endregion
        


        #region constructor / finalizer
        private void _initReportWatcher()
        {
            //first off set alert text
            _setAlertText();

            //load options
            _getPagesToCheck();
            _getReportsToCache();
            _getTroopCountMin();
            _getBoolAlertToAllianceChat();
            _getBoolAlertPlaySound();

            //subscribe to timer event
            _tmrReportCheck.Elapsed += new System.Timers.ElapsedEventHandler(_tmrReportCheck_Elapsed);
        }
        #endregion
        
        
        
        #region event handling
        void _tmrReportCheck_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //_tmrReportCheck.Enabled = false;
            _receiveReports(true);
        }
        #endregion
        
        
        
        #region private functions
        #region options
        /// <summary>_getPagesToCheck</summary>
        /// <history>created  07.02.2012</history>
        private void _getPagesToCheck()
        {
            int intPages2Check = 0;
            if (int.TryParse(_KRNL.LAO.GetOption(LAO_REPORT_WATCHER_PAGES_TO_CHECK), out intPages2Check))
            {
                if (intPages2Check > 0)
                {
                    _intReportPagesToCheck = intPages2Check;
                }
            }
        }

        /// <summary>_getReportsToCache</summary>
        /// <history>created  07.02.2012</history>
        private void _getReportsToCache()
        {
            int intReports2Cache = 0;
            if (int.TryParse(_KRNL.LAO.GetOption(LAO_REPORT_WATCHER_REPORTS_TO_CACHE), out intReports2Cache))
            {
                if (intReports2Cache > 0)
                {
                    _intReportsToCache = intReports2Cache;
                }
            }
        }

        /// <summary></summary>
        /// <history>created  25.04.2012</history>
        private void _getTroopCountMin()
        {
            int intTroopCountMin = 0;
            if (int.TryParse(_KRNL.LAO.GetOption(LAO_REPORT_WATCHER_TROOP_COUNT_MIN), out intTroopCountMin))
            {
                if (intTroopCountMin > 0)
                {
                    _intAttackTroopCountMin = intTroopCountMin;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <history>created  25.04.2012</history>
        private void _getBoolAlertToAllianceChat()
        {
            bool fAlert = false;
            if (bool.TryParse(_KRNL.LAO.GetOption(LAO_ALERT_TO_ALLIANCE_CHAT), out fAlert))
            {
                _fAlertToAllianceChat = fAlert;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <history>created  25.04.2012</history>
        private void _getBoolAlertPlaySound()
        {
            bool fAlert = false;
            if (bool.TryParse(_KRNL.LAO.GetOption(LAO_ALERT_PLAY_SOUND), out fAlert))
            {
                _fAlertPlaySound = fAlert;
            }
        }
        #endregion

        #region initializations
        /// <summary>_PreparePhpCommands</summary>
        /// <history>24.06.2011</history>
        /// <history>modified 31.01.2012 removed UrlHolder support and switched to new PhpCommandGenerator</history>
        private void _PreparePhpCommands()
        {
            try
            { 
                //if (_upiSelectedUser != null && PhpCommandGenerator.IsInitialized)
                if (_KK2VM.SelectedUser != null && PhpCommandGenerator.IsInitialized)
                {
                    //_pcListReports = PhpCommandGenerator.GetPhpCommand(_KRNL.EC, PhpCommands.listReports, _intServerId, _upiSelectedUser.FbUid);
                    //_pcFetchReport = PhpCommandGenerator.GetPhpCommand(_KRNL.EC, PhpCommands.fetchReport, _intServerId, _upiSelectedUser.FbUid);
                    _pcListReports = PhpCommandGenerator.GetPhpCommand(_KRNL.EC, PhpCommands.listReports, _KK2VM.ServerId, _KK2VM.SelectedUser.FbUid);
                    _pcFetchReport = PhpCommandGenerator.GetPhpCommand(_KRNL.EC, PhpCommands.fetchReport, _KK2VM.ServerId, _KK2VM.SelectedUser.FbUid);
                    //_pcDeleteCheckedReports = PhpCommandGenerator.GetPhpCommand(_KRNL.EC, PhpCommands.deleteCheckedReports, _intServerId, _upiSelectedUser.FbUid);
                }
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }
        #endregion

        #region receiving reports
        /// <summary>_receiveReports</summary>
        /// <history>07.02.2012</history>
        private void _receiveReports()
        {
            _receiveReports(false);
        }

        /// <summary>_receiveReports</summary>
        /// <history>07.02.2012</history>
        /// <history>modified 09.02.2012: Only checked for AllianceId and not for MarchType</history>
        private void _receiveReports(
            bool ThrowAlert)
        {
            try
            {
                //if (_thrReceiveReports.ThreadState == System.Threading.ThreadState.Running)
                //{
                //}

                //_thrReceiveReports = new Thread((ParameterizedThreadStart)delegate
                //{
                    try
                    {
                        //Prepare commands with the current KernelControl settings
                        _PreparePhpCommands();
                        _pcListReports.Parameters[PhpCommandParameters.GROUP] = "a";//parameter to get alliance reports

                        //prepare local variables
                        bool fExistingReportFound = false;

                        //iterate through the report pages
                        for (int intReportPage = 1; intReportPage <= _intReportPagesToCheck; intReportPage++)
                        {
                            //show status
                            _setStatusText("Analyzing reports page " + intReportPage);

                            //set report page parameter
                            _pcListReports.Parameters[PhpCommandParameters.PAGE_NO] = intReportPage.ToString();

                            #region logging
                            if (_fLoggingEnabled)
                                _KRNL.ML.AddMessage("ReportWatcher: sending listReports command pageno=" + intReportPage.ToString());
                            #endregion

                            //prepare resultset and get answer
                            Hashtable htReportList = null;
                            string strResult = "";
                            if (_pcListReports.GetAnswerHashtableAndString(out htReportList, out strResult))
                            {
                                #region logging
                                if (_fLoggingEnabled)
                                {
                                    _KRNL.ML.AddMessage("ReportWatcher: received listReports command result for pageno=" + intReportPage.ToString() + " (resultstring:\"" + strResult.Trim() + "\")");
                                }
                                #endregion

                                if (_KRNL.ReturnHashtableOk(htReportList))
                                {
                                    //First off get CityNames, PlayerNames and AllianceNames Lists of resultset
                                    _dictCityNames = _GetDictionary(htReportList, constants.KEY_CITY_NAMES, "c");
                                    _dictPlayerNames = _GetDictionary(htReportList, constants.KEY_PLAYER_NAMES, "p");
                                    _dictAllianceNames = _GetDictionary(htReportList, constants.KEY_ALLIANCE_NAMES, "a");

                                    //get max pages
                                    int intPageMax = _KRNL.GetHashtableValue(htReportList, constants.KEY_TOTAL_PAGES, KernelTools.VariableTypes.Int32);
                                    if (_intReportListPageMax != intPageMax)
                                    {
                                        _intReportListPageMax = intPageMax;
                                    }

                                    //check if max pages are ok
                                    if (_intReportPagesToCheck > _intReportListPageMax)
                                    {
                                        _intReportPagesToCheck = _intReportListPageMax;
                                        OnPropertyChanged("ReportPagesToCheck");
                                    }

                                    //prepare reports resultset and get reports
                                    Hashtable htReports = htReportList[constants.KEY_REPORTS] as Hashtable;
                                    if (htReports != null)
                                    {
                                        //iterate through reports
                                        foreach (DictionaryEntry deReport in htReports)
                                        {
                                            //get one report result
                                            Hashtable htReportEntry = deReport.Value as Hashtable;

                                            //get report id
                                            string strReportId = _KRNL.GetHashtableValue(htReportEntry, constants.KEY_REPORT_ID, KernelTools.VariableTypes.String);

                                            //show status
                                            _setStatusText("Analyzing reports page " + intReportPage + "  Report " + strReportId);

                                            //First off, check if ReportID already exists in report list 
                                            if (_dictReportCache.ContainsKey(strReportId))
                                            {
                                                //Report exists, so it is most likely that there are no further new reports
                                                fExistingReportFound = true;
                                                //anyways, we got the reportlist, so just skip this one and continue. ;)
                                                continue;
                                            }

                                            //Build Reportitem
                                            ReportItem RI = _getReportItemBase(htReportEntry);

#if DEBUG
                                            Debug.WriteLine(
                                                "RID: {0,-10}, Type:{1,-10}, Deffender: {2,-10}, Attacker: {3,-10}",
                                                RI.RLI.reportId,
                                                RI.RLI.MarchTypeName,
                                                RI.RLI.S0PlayerName,
                                                RI.RLI.S1PlayerName);
#endif

                                            //add to collection
                                            _dictReportCache.Add(strReportId, RI);

                                            //finally throw alert
                                            if (ThrowAlert)
                                            {
                                                //Detail filter switch
                                                bool fDetailFilterOK = false;

                                                //try to load report (must go into ThrowAlert section when done)
                                                Hashtable htReport = _GetReport((int)RI.RLI.reportId, 0);
                                                if (htReport != null &&
                                                    _KRNL.ReturnHashtableOk(htReport))
                                                {
                                                    //Put report to ReportItem
                                                    RI.Report = htReport;

                                                    //get further filter criteria
                                                    int intOffensiveTroopCount = RI.GetReportOffensiveTroopCount();
                                                    if (intOffensiveTroopCount >= _intAttackTroopCountMin)
                                                    {
                                                        fDetailFilterOK = true;
                                                    }
                                                }

                                                //but only if current users alliance is attacked
                                                if (RI.RLI.marchType == MarchTypes.Attack.GetHashCode() &&
                                                    //RI.RLI.side0AllianceId.ToString() == _upiSelectedUser.allianceId &&
                                                    RI.RLI.side0AllianceId.ToString() == _KK2VM.SelectedUser.allianceId &&
                                                    fDetailFilterOK)
                                                {
                                                    //_throwAlert(RI);
                                                    _throwAlerts(RI);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            //if throwing allerts and (TODO) one existing report is found in collection, break after loop
                            if (ThrowAlert && fExistingReportFound)
                            {
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
                    }

                    //show status
                    _setStatusText("Analyzing done!");

                    //Re-Enable timer if switch is active
                    if (_fReportWatcherActive)
                    {
                        //_tmrReportCheck.Enabled = true;
                    }
                //});

                //_thrReceiveReports.Name = "_receiveReports (" + DateTime.Now + ")";
                //_thrReceiveReports.Start();
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="htReportEntry"></param>
        /// <returns></returns>
        /// <history>created  21.04.2012</history>
        private ReportItem _getReportItemBase(
            Hashtable htReportEntry)
        {
            try
            {
                //Build ReportListItem
                ReportListItem RLI = new ReportListItem(_KRNL, htReportEntry);

                // Get manual Info afterwards
                //get city names
                if (_dictCityNames.ContainsKey((Int32)RLI.side0CityId))
                {
                    RLI.S0CityName = _dictCityNames[(Int32)RLI.side0CityId];
                }
                if (_dictCityNames.ContainsKey((Int32)RLI.side1CityId))
                {
                    RLI.S1CityName = _dictCityNames[(Int32)RLI.side1CityId];
                }

                //get player names
                if (_dictPlayerNames.ContainsKey((Int32)RLI.side0PlayerId))
                {
                    RLI.S0PlayerName = _dictPlayerNames[(Int32)RLI.side0PlayerId];
                }
                if (_dictPlayerNames.ContainsKey((Int32)RLI.side1PlayerId))
                {
                    RLI.S1PlayerName = _dictPlayerNames[(Int32)RLI.side1PlayerId];
                }

                //get alliance names
                if (_dictAllianceNames.ContainsKey((Int32)RLI.side0AllianceId))
                {
                    RLI.S0AllianceName = _dictAllianceNames[(Int32)RLI.side0AllianceId];
                }
                if (_dictAllianceNames.ContainsKey((Int32)RLI.side1AllianceId))
                {
                    RLI.S1AllianceName = _dictAllianceNames[(Int32)RLI.side1AllianceId];
                }

                //calculate real date of timestamp
                RLI.ReportDateTime = _KRNL.Timestamp2DateString((Int32)RLI.reportUnixTime);

                //get march type name
                RLI.MarchTypeName = ((MarchTypes)RLI.marchType).ToString();

                return new ReportItem(RLI);
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }

            return null;
        }

        /// <summary>_GetReport</summary>
        /// <history>created  02.02.2012</history>
        /// <history>modified 08.02.2012 </history>
        private Hashtable _GetReport(
            int ReportId,
            int side)
        {
            try
            {
                if (side < 0 || side > 1)
                {
                    side = 0;
                }

                //Get single reports.
                Hashtable htReport;
                //_pcFetchReport = PhpCommandGenerator.GetPhpCommand(_KRNL.EC, PhpCommands.fetchReport, _intServerId, _upiSelectedUser.FbUid);
                _pcFetchReport = PhpCommandGenerator.GetPhpCommand(_KRNL.EC, PhpCommands.fetchReport, _KK2VM.ServerId, _KK2VM.SelectedUser.FbUid);
                _pcFetchReport.Parameters[PhpCommandParameters.RID] = ReportId.ToString();
                _pcFetchReport.Parameters[PhpCommandParameters.SIDE] = side.ToString();

                #region logging
                if (_fLoggingEnabled)
                    _KRNL.ML.AddMessage("ReportWatcher: fetching report rid=" + ReportId.ToString() + ", side=" + side.ToString());
                #endregion

                string strResult = "";
                _pcFetchReport.GetAnswerHashtableAndString(out htReport, out strResult);

                #region logging
                if (_fLoggingEnabled)
                    _KRNL.ML.AddMessage("ReportWatcher: received report rid=" + ReportId.ToString() + ", side=" + side.ToString() + " (result=\"" + strResult.Trim() + "\")");
                #endregion

                _setStatusText("Report holen (RId: " + ReportId.ToString() + ", side: " + side.ToString() + ")");

                return htReport;
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }

            return null;
        }

        private int _getReportOffensiveTroopCount(
            Hashtable htReport)
        {
            try
            {
                //get fight details
                Hashtable htFght = htReport[constants.KEY_FGHT] as Hashtable;
                if (htFght != null)
                {
                    //get offensive troops (s1)
                    Hashtable htS1OffTroops = htFght["s1"] as Hashtable;
                    if (htS1OffTroops != null)
                    {
                        int TroopCount = 0;

                        foreach (DictionaryEntry DE in htS1OffTroops)
                        {
                            ArrayList aryValue = DE.Value as ArrayList;
                            if (aryValue != null)
                            {
                                TroopCount += _KRNL.GetObjectValue(aryValue[1], KernelTools.VariableTypes.Int32);
                            }
                        }

                        return TroopCount;
                    }
                }
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }

            return -1;
        }

        /// <summary>_GetDictionary</summary>
        /// <param name="htSource"></param>
        /// <param name="ListKey"></param>
        /// <param name="ItemKeyPrefix"></param>
        /// <returns></returns>
        private Dictionary<Int32, String> _GetDictionary(
            Hashtable htSource,
            String ListKey,
            String ItemKeyPrefix)
        {
            try
            {
                Dictionary<Int32, String> dictRetVal = new Dictionary<Int32, String>();

                Hashtable htDict = htSource[ListKey] as Hashtable;
                if (htDict != null)
                {
                    foreach (DictionaryEntry DE in htDict)
                    {
                        if (DE.Key.ToString().StartsWith(ItemKeyPrefix))
                        {
                            dictRetVal.Add(_KRNL.GetObjectValue(DE.Key.ToString().Replace(ItemKeyPrefix, ""), KernelTools.VariableTypes.Int32), DE.Value.ToString());
                        }
                    }
                }

                return dictRetVal;
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }

            return null;
        }
        #endregion

        #region preparing and throwing alerts
        /// <summary>
        /// 
        /// </summary>
        /// <param name="RI"></param>
        /// <param name="AlertText"></param>
        /// <history>created  21.04.2012</history>
        /// <history>modified 25.04.2012: added sound alert</history>
        private void _throwAlerts(
            ReportItem RI)
        {
            try
            {
#if DEBUG
                Debug.WriteLine(
                    "RID: {0,-10}, Type:{1,-10}, Deffender: {2,-10}, Attacker: {3,-10}   ALERT !!!!", 
                    RI.RLI.reportId, 
                    RI.RLI.MarchTypeName, 
                    RI.RLI.S0PlayerName, 
                    RI.RLI.S1PlayerName);
#endif
                //Generate coord strings
                String strS0Coords = String.Concat(RI.RLI.side0XCoord, ",", RI.RLI.side0YCoord);
                String strS1Coords = String.Concat(RI.RLI.side1XCoord, ",", RI.RLI.side1YCoord);

                //replace alert text placeholders
                _strAlertText = _strAlertText.Replace(ALERT_PLACE_REPORT_ID, RI.RLI.reportId.ToString());
                _strAlertText = _strAlertText.Replace(ALERT_PLACE_S0_COORDS, strS0Coords);
                _strAlertText = _strAlertText.Replace(ALERT_PLACE_S0_ALLIANCE_NAME, RI.RLI.S0AllianceName);
                _strAlertText = _strAlertText.Replace(ALERT_PLACE_S0_PLAYER_NAME, RI.RLI.S0PlayerName);
                _strAlertText = _strAlertText.Replace(ALERT_PLACE_S0_CITY_NAME, RI.RLI.S0CityName);
                _strAlertText = _strAlertText.Replace(ALERT_PLACE_S1_COORDS, strS1Coords);
                _strAlertText = _strAlertText.Replace(ALERT_PLACE_S1_ALLIANCE_NAME, RI.RLI.S1AllianceName);
                _strAlertText = _strAlertText.Replace(ALERT_PLACE_S1_PLAYER_NAME, RI.RLI.S1PlayerName);
                _strAlertText = _strAlertText.Replace(ALERT_PLACE_S1_CITY_NAME, RI.RLI.S1CityName);
                _strAlertText = _strAlertText.Replace(ALERT_PLACE_S1_TROOP_COUNT, RI.GetReportOffensiveTroopCount().ToString());

                //Show something
                _setStatusText(_strAlertText);

                //sendChat
                _alertToAlliChat(_strAlertText);

                //play sound
                _alertPlaySound();
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>sets the alert text. calls the function to read the alert text file and sets a default when the file is not found.</summary>
        /// <history>created  21.04.2012</history>
        private void _setAlertText()
        {
            try
            {
                //First try to read AlertText file
                _strAlertText = _readAlertTextFile().Trim();

                //Check if there is a text, otherwise set default text
                if (_strAlertText.Trim() == "")
                {
                    _strAlertText = string.Concat(
                        "Watcher of the reports ALERT !!!! ",
                        "Angriff (RID: ", ALERT_PLACE_REPORT_ID,
                        ") auf ", ALERT_PLACE_S0_COORDS,
                        " mit ", ALERT_PLACE_S1_TROOP_COUNT, " Truppen",
                        " (", ALERT_PLACE_S0_CITY_NAME,
                        ",", ALERT_PLACE_S0_PLAYER_NAME,
                        ",", ALERT_PLACE_S0_ALLIANCE_NAME,
                        ")  Angreifer: ", ALERT_PLACE_S1_PLAYER_NAME,
                        ",", ALERT_PLACE_S1_ALLIANCE_NAME,
                        " (", ALERT_PLACE_S1_COORDS,
                        " / ", ALERT_PLACE_S1_CITY_NAME, ")");
                }
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>reads the alert text file if existing, omitting comments and empty rows. Also removing NewLines</summary>
        /// <returns>string containing a clean alert text or an empty string if alert text file was not found</returns>
        /// <history>created  21.04.2012</history>
        private string _readAlertTextFile()
        {
            try
            {
                //create file name
                string strFileName = string.Concat(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName, "\\", ALERT_TEXT_FILE_NAME);

                //check if file exist
                if (File.Exists(strFileName))
                {
                    //prepare return value
                    string strReturnValue = "";

                    //get text stream
                    using (TextReader TR = new StreamReader(strFileName))
                    {
                        string strLine = "";

                        //run through stream linewise
                        while ((strLine = TR.ReadLine()) != null)
                        {
                            //remove comments and emtpy lines
                            if (strLine.StartsWith("#") ||
                                strLine.Trim() == "")
                            {
                                continue;
                            }

                            //remove linebreaks
                            strLine = strLine.Replace(Environment.NewLine, "");

                            //remember only text without linebreak
                            strReturnValue = string.Concat(strReturnValue, strLine);
                        }

                        TR.Close();
                        TR.Dispose();
                    }

                    //return text
                    return strReturnValue;
                }
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }

            return "";
        }
        #endregion

        #region alerts
        /// <summary>_alertToAlliChat</summary>
        /// <param name="AlertText"></param>
        /// <history>created  09.02.2012</history>
        /// <history>modified 25.04.2012: added switch to en/dis-able alert</history>
        private void _alertToAlliChat(
            string AlertText)
        {
            if (_fAlertToAllianceChat)
            {
                using (PhpCommand pcSendChat = PhpCommandGenerator.GetPhpCommand(_KRNL.EC, PhpCommands.sendChat, _KK2VM.ServerId, _KK2VM.SelectedUser.FbUid))
                {
                    pcSendChat.Parameters[PhpCommandParameters.CTYPE] = "2";
                    pcSendChat.Parameters[PhpCommandParameters.NAME] = "";
                    pcSendChat.Parameters[PhpCommandParameters.COMMENT] = AlertText;
                    pcSendChat.Parameters[PhpCommandParameters.CTYPE_ID] = "1";
                    pcSendChat.Parameters[PhpCommandParameters.NM] = "";
                    pcSendChat.Parameters[PhpCommandParameters.SID] = _KK2VM.ServerId.ToString();

                    #region logging
                    if (_fLoggingEnabled)
                        _KRNL.ML.AddMessage(
                            String.Format("ReportWatcher: sendint alert to alliance chat ctype={0}, comment=\"{1}\", sid={2}", "2", AlertText, _KK2VM.ServerId.ToString()));
                    #endregion

                    string strResult = "";
                    Hashtable htResult = null;
                    if (pcSendChat.GetAnswerHashtableAndString(out htResult, out strResult))
                    {
                        #region logging
                        if (_fLoggingEnabled)
                            _KRNL.ML.AddMessage("ReportWatcher: received sendchat response: \"" + strResult.Trim() + "\"");
                        #endregion

                        if (htResult == null ||
                            !_KRNL.ReturnHashtableOk(htResult))
                        {
                            _setStatusText("sendChat FAILED!!!");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <history>created  25.04.2012</history>
        /// <history>modified 25.04.2012: added switch to en/dis-able alert</history>
        private void _alertPlaySound()
        {
            try
            {
                if (_fAlertPlaySound)
                {
                    //create file name
                    string strFileName = string.Concat(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName, "\\", ALERT_SOUND_FILE_NAME);

                    if (File.Exists(strFileName))
                    {
                        SoundPlayer player = new SoundPlayer();
                        player.SoundLocation = strFileName;
                        player.Play();
                    }
                }
            }
            catch (Exception ex)
            {
                _KRNL.EC.AddException(ex, this.ToString(), _KRNL.EC.Tools.GetCurrentMethodName());
            }
        }
        #endregion
        #endregion



        #region interface
        #region properties
        public bool KernelSettingsAlowed
        {
            get
            {
                return !_fReportWatcherActive;
            }
        }

        public bool ReportWatcherActive
        {
            get
            {
                return _fReportWatcherActive;
            }
            set
            {
                if (_fReportWatcherActive != value)
                {
                    _fReportWatcherActive = value;
                    OnPropertyChanged("KernelSettingsAlowed");

                    if (_fReportWatcherActive)
                    {
                        _receiveReports();
                        _tmrReportCheck.Enabled = true;
                    }
                    else
                    {
                        _tmrReportCheck.Enabled = false;
                    }
                }
            }
        }

        public int ReportPagesToCheck
        {
            get
            {
                return _intReportPagesToCheck;
            }
            set
            {
                if (_intReportPagesToCheck != value)
                {
                    _intReportPagesToCheck = value;
                    _KRNL.LAO.SetOption(LAO_REPORT_WATCHER_PAGES_TO_CHECK, _intReportPagesToCheck.ToString());
                }
            }
        }

        public int ReportsToCache
        {
            get
            {
                return _intReportsToCache;
            }
            set
            {
                if (_intReportsToCache != value)
                {
                    _intReportsToCache = value;
                    _KRNL.LAO.SetOption(LAO_REPORT_WATCHER_REPORTS_TO_CACHE, _intReportsToCache.ToString());
                }
            }
        }

        public int MinimumAttackTroops
        {
            get { return _intAttackTroopCountMin; }
            set
            {
                if (_intAttackTroopCountMin != value)
                {
                    _intAttackTroopCountMin = value;
                    _KRNL.LAO.SetOption(LAO_REPORT_WATCHER_TROOP_COUNT_MIN, _intAttackTroopCountMin.ToString());
                }
            }
        }

        public bool AlertToAllianceChat
        {
            get { return _fAlertToAllianceChat; }
            set
            {
                if (_fAlertToAllianceChat != value)
                {
                    _fAlertToAllianceChat = value;
                    _KRNL.LAO.SetOption(LAO_ALERT_TO_ALLIANCE_CHAT, _fAlertToAllianceChat.ToString());
                }
            }
        }

        public bool AlertPlaySound
        {
            get { return _fAlertPlaySound; }
            set
            {
                if (_fAlertPlaySound != value)
                {
                    _fAlertPlaySound = value;
                    _KRNL.LAO.SetOption(LAO_ALERT_PLAY_SOUND, _fAlertPlaySound.ToString());
                }
            }
        }

        public bool LoggingEnabled
        {
            get { return _fLoggingEnabled; }
            set { _fLoggingEnabled = value; }
        }
        
        #endregion

        #region methods
        #endregion
        #endregion
   }
}
